package com.lishe.lishe.lishe.service;

import android.app.DownloadManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.text.TextUtils;

import com.lishe.lishe.lishe.common.Globals;

import java.io.File;

/**
 * Created by lwa on 2017/9/4.
 * app通知栏的升级服务
 */

public class AppUpdataService extends Service {

    private String url;
    private DownloadManager downloadManager;//系统下载器管理
    /**
     * 系统下载器分配的唯一下载任务id，可以通过这个id查询或者处理下载任务
     */
    private long taskId;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        url = intent.getStringExtra("url");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 开始现在任务
     */
    private void startLoading() {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        //获取下载器管理
        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        //设置下载链接
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        //设置文件类型
        request.setMimeType("application/vnd.android.package-archive");
        //文件保存位置及文件名设置
        request.setDestinationInExternalPublicDir(Globals.LISHE_FILE, Globals.APK_NAME);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setTitle("礼舍");
        //执行下载任务
        taskId = downloadManager.enqueue(request);
    }

    /**
     * 安装App
     */
    public static void install(Context context) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(new File(Globals.LISHE_FILE, Globals.APK_NAME)), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    /**
     * 开启服务
     */
    public static void starDownloadService(Context context, String url) {
        Intent intent = new Intent(context, AppUpdataService.class);
        intent.putExtra("url", url);
        context.startService(intent);
    }

    /**
     * 停止服务
     *
     * @param context
     */
    public static void stopDownLoadService(Context context) {
        Intent intent = new Intent(context, AppUpdataService.class);
        context.startService(intent);
    }
}
